package game

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"go.uber.org/zap"
	"google.golang.org/grpc/status"
	"qm_system_server/server/global"
	"qm_system_server/server/model/common/response"
	"qm_system_server/server/proto/grpc/server"
	"qm_system_server/server/service"
	"qm_system_server/server/utils"
)

type QmServerApi struct {
}

var qmServerService = service.ServiceGroupApp.GameServiceGroup.QmServerService

// CreateQmServer 创建qmServer表
// @Tags QmServer
// @Summary 创建qmServer表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body game.QmServer true "创建qmServer表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /qmServer/createQmServer [post]
func (qmServerApi *QmServerApi) CreateQmServer(c *gin.Context) {
	//var qmServer game.QmServer
	//err := c.ShouldBindJSON(&qmServer)
	//if err != nil {
	//	response.FailWithMessage(err.Error(), c)
	//	return
	//}

	//if err := qmServerService.CreateQmServer(&qmServer); err != nil {
	//    global.GVA_LOG.Error("创建失败!", zap.Error(err))
	//	response.FailWithMessage("创建失败", c)
	//} else {
	//	response.OkWithMessage("创建成功", c)
	//}
	type request struct {
		GameHash   string `json:"game_hash" from:"game_hash"`
		PlatformId int64  `json:"platform_id" form:"platform_id"`
		ServerName string `json:"server_name" form:"server_name"`
		ServerHash string `json:"server_hash" form:"server_hash"`
		Status     int64  `json:"status" form:"status"`
	}
	var req request
	_ = c.ShouldBindJSON(&req)

	//获取header中的game-id
	req.GameHash = c.Request.Header.Get("game-hash")
	req.PlatformId = cast.ToInt64(c.Request.Header.Get("platform-id"))

	req.ServerHash = utils.GenerateRandomString(15)

	if req.ServerName == "" || req.ServerHash == "" || req.Status == 0 || req.PlatformId == 0 || req.GameHash == "" {
		response.FailWithMessage("参数不能为空", c)
		return
	}

	client := server.NewServerServiceClient(global.ServerGrpc)

	_, err := client.Create(context.Background(), &server.CreateRequest{
		Server: &server.Server{
			GameHash:   req.GameHash,
			PlatformId: req.PlatformId,
			ServerName: req.ServerName,
			ServerHash: req.ServerHash,
			Status:     req.Status,
		},
	})

	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			// 获取 gRPC 错误的描述信息
			response.FailWithMessage(st.Message(), c)
		}
		return
	}
	response.OkWithMessage("创建成功", c)
}

// DeleteQmServer 删除qmServer表
// @Tags QmServer
// @Summary 删除qmServer表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body game.QmServer true "删除qmServer表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /qmServer/deleteQmServer [delete]
func (qmServerApi *QmServerApi) DeleteQmServer(c *gin.Context) {
	ID := c.Query("id")

	//转成int64
	id := cast.ToInt64(ID)

	client := server.NewServerServiceClient(global.ServerGrpc)

	_, err := client.Delete(context.Background(), &server.DeleteRequest{
		Id: id,
	})

	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			// 获取 gRPC 错误的描述信息
			response.FailWithMessage(st.Message(), c)
		}
		return
	}
	response.OkWithMessage("删除成功", c)
}

// DeleteQmServerByIds 批量删除qmServer表
// @Tags QmServer
// @Summary 批量删除qmServer表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Success 200 {string} string "{"success":true,"data":{},"msg":"批量删除成功"}"
// @Router /qmServer/deleteQmServerByIds [delete]
func (qmServerApi *QmServerApi) DeleteQmServerByIds(c *gin.Context) {
	IDs := c.QueryArray("IDs[]")
	if err := qmServerService.DeleteQmServerByIds(IDs); err != nil {
		global.GVA_LOG.Error("批量删除失败!", zap.Error(err))
		response.FailWithMessage("批量删除失败", c)
	} else {
		response.OkWithMessage("批量删除成功", c)
	}
}

// UpdateQmServer 更新qmServer表
// @Tags QmServer
// @Summary 更新qmServer表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body game.QmServer true "更新qmServer表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /qmServer/updateQmServer [put]
func (qmServerApi *QmServerApi) UpdateQmServer(c *gin.Context) {
	type request struct {
		Id         int64  `json:"id" form:"id"`
		ServerName string `json:"server_name" form:"server_name"`
		Status     int64  `json:"status" form:"status"`
	}

	var req request

	_ = c.ShouldBindJSON(&req)

	if req.Id == 0 || req.ServerName == "" || req.Status == 0 {
		response.FailWithMessage("参数不能为空", c)
		return
	}

	grpcClient := server.NewServerServiceClient(global.ServerGrpc)

	_, err := grpcClient.Update(context.Background(), &server.UpdateRequest{
		Server: &server.Server{
			Id:         req.Id,
			ServerName: req.ServerName,
			Status:     req.Status,
		},
	})

	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			// 获取 gRPC 错误的描述信息
			response.FailWithMessage(st.Message(), c)
		}
		return
	}

	response.OkWithMessage("更新成功", c)
}

// FindQmServer 用id查询qmServer表
// @Tags QmServer
// @Summary 用id查询qmServer表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query game.QmServer true "用id查询qmServer表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /qmServer/findQmServer [get]
func (qmServerApi *QmServerApi) FindQmServer(c *gin.Context) {
	type request struct {
		Id int64 `json:"id" form:"id"`
	}

	var req request

	c.ShouldBindQuery(&req)

	//判断不能为空
	if req.Id == 0 {
		response.FailWithMessage("参数不能为空", c)
		return
	}

	grpcClient := server.NewServerServiceClient(global.ServerGrpc)
	getResp, err := grpcClient.Get(context.Background(), &server.GetRequest{
		Id: req.Id,
	})

	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			// 获取 gRPC 错误的描述信息
			response.FailWithMessage(st.Message(), c)
		}
		return
	}

	response.OkWithData(getResp.Server, c)
}

// GetQmServerList 分页获取qmServer表列表
// @Tags QmServer
// @Summary 分页获取qmServer表列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query gameReq.QmServerSearch true "分页获取qmServer表列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /qmServer/getQmServerList [get]
func (qmServerApi *QmServerApi) GetQmServerList(c *gin.Context) {
	type request struct {
		Status     int64  `json:"status" form:"status"`
		Page       int64  `json:"page" form:"page"`
		PlatformId int64  `json:"platformId" form:"platform_id"`
		ServerName string `json:"serverName" form:"serverName"`
		GameHash   string `json:"gameHash" form:"game_hash"`
		PageSize   int64  `json:"pageSize" form:"pageSize"`
	}

	var req request

	_ = c.ShouldBindQuery(&req)

	req.GameHash = c.Request.Header.Get("game-hash")
	req.PlatformId = cast.ToInt64(c.Request.Header.Get("platform-id"))

	grpcClient := server.NewServerServiceClient(global.ServerGrpc)

	servers, err := grpcClient.List(context.Background(), &server.ListRequest{
		Status:     req.Status,
		Platform:   req.PlatformId,
		Page:       req.Page,
		ServerName: req.ServerName,
		GameHash:   req.GameHash,
		PageSize:   req.PageSize,
	})

	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			// 获取 gRPC 错误的描述信息
			response.FailWithMessage(st.Message(), c)
		}
		return
	}

	response.OkWithData(response.PageResult{
		List:  servers.Server,
		Total: servers.Total,
		Page:  int(req.Page),
	}, c)

}
